﻿"""
机台校准数据计算系统
"""
# 导入系统模块
import os
import uuid
from datetime import datetime
from flask import Flask, render_template, url_for, session, request, redirect
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, TextAreaField, RadioField, BooleanField
from wtforms.validators import DataRequired, Length
from flask_wtf.file import FileField, FileRequired, FileAllowed

# 导入自制模块
from sortingdataprocess import get_test_data, get_moid
from uploadstddata import upload_stddata, add_moid
from weblog import get_logger

# 初始化日志功能，启动日志记录
logger = get_logger(__name__)
logger.info("....")

# Flask实例化，加密Cookie
app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY', 'secret string')
# 删除Jinja2语句中的空格和制表符
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True
# 上传附件最大10Mb上限
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024

# 所有机台的IP地址,排测机使用
# ip_dict = {'192.168.30.101': 1, '192.168.30.57': 2, '192.168.30.148': 3, '192.168.30.198': 4, '192.168.30.134': 5,
#            '192.168.30.195': 6, '192.168.30.16': 7, '192.168.30.76': 8, '192.168.30.151': 9,'192.168.30.10': 10,
#            '192.168.30.66': 11, '192.168.30.83': 12, '192.168.30.196': 13, '192.168.20.219': 14,'192.168.20.138': 15,
#            '192.168.30.108': 16, '192.168.30.3': 17, '192.168.30.179': 18, '192.168.60.98': 19, '192.168.30.45': 20,
#            '192.168.30.72': 21, '192.168.60.183':22, '192.168.30.154': 23}

ip_dict = {'192.168.20.219': 14, '192.168.30.108': 16}


# 定义工单下载输入界面表单类，设置相关验证要求
class Form1(FlaskForm):
    item_code = StringField('标准件型号', validators=[DataRequired()])
    user_id = StringField('工号', validators=[DataRequired(), Length(5, 5)])
    moid = StringField('工单号')
    excel_data = FileField('附件', validators=[FileRequired(), FileAllowed(['xls', 'csv'])])
    pluse = BooleanField(label="脉冲测试")
    notes = RadioField('标准件类别', choices=[('一次性', '一次性'), ('新增标准件', '新增标准件'), ('过期标准件', '过期标准件'), ('更新替换', '更新替换'),
                                         ('机差点检', '机差点检')],
                       validators=[DataRequired()])
    submit = SubmitField('提交')


# 定义添加工单的Form2
class Form2(FlaskForm):
    item_code = StringField('标准件型号', validators=[DataRequired()])
    moid = StringField('工单号', validators=[DataRequired()])
    submit = SubmitField('提交')


# 定义文件修改函数，新文件名为 工单号+批号+扩展名
def alter_filename(filename):
    ext = os.path.splitext(filename)[1]
    new_filename = uuid.uuid4().hex + ext
    return new_filename


# 注册/data路由和data视图函数
@app.route('/', methods=['GET', 'POST'])
def data():
    machine_ip = request.remote_addr
    if machine_ip in ip_dict:
        machine_id = ip_dict[machine_ip]
        # logger.info(f"{machine_id}号机进入系统！")
    else:
        logger.error(f"{machine_ip}--非法访问！")
        return redirect(url_for('reject'))

    form1 = Form1()
    # 根据年月份自动创建上传文件目录
    uploadsDir = os.path.join('uploaddata', str(datetime.now().year), str(datetime.now().month))
    if os.path.exists(uploadsDir):
        pass
    else:
        os.makedirs(uploadsDir)
    app.config['UPLOAD_PATH'] = os.path.join(app.root_path, uploadsDir)

    if form1.validate_on_submit():
        # 获取上传文件信息
        f = form1.excel_data.data
        logger.info(f"{machine_id}号机--标准件类型：{form1.notes.data}--标准件数据：{f.filename}")
        # 修改文件名，设置上传文件路径
        filename = alter_filename(f.filename)
        path = os.path.join(app.config['UPLOAD_PATH'], filename)
        # 根据路径保存文件
        f.save(path)
        # 获取远方1号数据
        pluse = form1.pluse.data
        if form1.item_code.data.startswith('MY') and not pluse:
            return "<p>美一标准件请勾选脉冲</p>" + f'<br><a href="{url_for("data")}">返回</a>'
        test_data = get_test_data(path, machine_id, pluse)
        # print(test_data)
        # 判断CF2，CF3系数是存在
        if not test_data.empty:
            update_state = upload_stddata(form1.item_code.data, form1.user_id.data, form1.notes.data, test_data,
                                          machine_id, form1.moid.data, logger, pluse)
            if update_state > 0:
                logger.info('数据提交成功!')
                os.remove(path)
                return "<p>数据提交成功</p>" + f'<br><a href="{url_for("data")}">返回</a>'
            elif update_state == -1:
                # -1：一次性工单未输入工单号
                logger.warn("一次性标准件未输入对应工单号！")
                os.remove(path)
                return "<p>一次性标准件未输入对应工单号！</p>" + f'<br><a href="{url_for("data")}">返回</a>'
            else:
                # -2：数据库写入失败
                logger.warn("数据写入数据库失败！")
                os.remove(path)
                return "<p>写入数据库失败</p>" + f'<br><a href="{url_for("data")}">返回</a>'
        else:
            logger.warn("获取上传数据失败！")
            os.remove(path)
            return "<p>数据文件格式有误</p>" + f'<br><a href="{url_for("data")}">返回</a>'
    return render_template('stddata.html', form1=form1)


# 注册/data路由和data视图函数
@app.route('/add', methods=['GET', 'POST'])
def add():
    form2 = Form2()
    if form2.validate_on_submit():
        moid_data = get_moid(form2.item_code.data)
        if not moid_data.empty:
            moid = moid_data.loc[0,'MoID']
            print(moid)
            try:
                add_moid(form2.item_code.data, form2.moid.data, moid)
            except Exception as e:
                print(e)
                return "<p>工单号更新失败！</p>" + f'<br><a href="{url_for("data")}">返回</a>'
            else:
                return "<p>成功更新</p>" + f'<br><a href="{url_for("data")}">返回</a>'
    return render_template('add.html', form2=form2)


# 注册/reject路由和reject视图函数
@app.route('/reject', methods=['GET'])
def reject():
    return render_template('reject.html')


# 主程序入口
if __name__ == '__main__':
    app.run()
